/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.sip;

import java.net.DatagramPacket;
import java.util.concurrent.ArrayBlockingQueue;
import javamail.conn.udpSocket;

/**
 *
 * @author sriram
 */
public class sipUASend extends Thread {
    private static final boolean debugEnabled = true;
    private udpSocket sock = null;
    private static ArrayBlockingQueue msgQ = null;

    private static final int MAX_MESSAGES_QUEUED = 100;
    private static final int MAX_MESSAGES_PER_CYCLE = 10;

    public sipUASend(udpSocket sock) {
        this.sock = sock;
        msgQ = new ArrayBlockingQueue(MAX_MESSAGES_QUEUED);
    }

    @Override
    public void run() {
        while(true) {
            try {
                // Sleep for 200 milliseconds before checking
                // for new messages to process
                sleep(200);
                checkForNewMessages();
            } catch(InterruptedException e) {
                checkForNewMessages();
            }
        }
    }

    public void checkForNewMessages() {
        DatagramPacket temp = null;
        for(int i=0; i<MAX_MESSAGES_PER_CYCLE; i++) {
            if((temp = (DatagramPacket) msgQ.poll()) != null) {
                if(debugEnabled)
                    System.out.println("sipUASend::checkForNewMessages-Total Queue size"+msgQ.size());
                sendMessage(temp);
            } else {
                break;
            }
        }
    }

    public boolean sendMessage (DatagramPacket pkt) {
        try {
            if(sock==null || sock.error==true) {
                if(debugEnabled)
                    System.out.println("sipUASend::run-SIP UDP socket not open");
                return false;
            }
            // Call the UDP socket routine sendPkt() for the actual send
            sock.sendPkt(pkt);
        } catch(Exception e) {
            if(debugEnabled)
                System.out.println("sipUASend::run-Error Occured-"+e.getMessage());
        }
        return true;
    }

    public static boolean send(DatagramPacket pkt) {
        try {
            if(debugEnabled)
                System.out.println("sipUASend::send-Message sucessfully queued");
            return msgQ.add(pkt);
        } catch (Exception e) {
            if(debugEnabled)
                System.out.println("sipUASend::send-Unable to queue the message: " + e.getMessage());
            return false;
        }
    }
}

